91. 解码方法
为保证权益,题目请参考 91. 解码方法(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
class Solution
{
public:
int numDecodings(string s)
{
if (s.length() == 0 || s[0] == '0')
{
return 0;
}
if (s.length() == 1)
{
return 1;
}
vector<int> dp(s.length() + 1, 0); // 前I个字符的可能性
dp[0] = 1;
dp[1] = 1;
for (int i = 2; i <= s.length(); i++)
{
if (s[i - 2] == '0')
{
if (s[i - 1] == '0')
{
return 0;
}
else
{
dp[i] = dp[i - 1];
}
}
else if (s[i - 2] == '1')
{
if (s[i - 1] == '0')
{
dp[i] = dp[i - 2];
}
else
{
dp[i] = dp[i - 1] + dp[i - 2];
}
}
else if (s[i - 2] == '2')
{
if (s[i - 1] == '0')
{
dp[i] = dp[i - 2];
}
else if (s[i - 1] <= '6')
{
dp[i] = dp[i - 1] + dp[i - 2];
}
else
{
dp[i] = dp[i - 1];
}
}
else
{
if (s[i - 1] == '0')
{
return 0;
}
else
{
dp[i] = dp[i - 1];
}
}
}
return dp[s.length()];
}
};
int main()
{
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
Python
python
# 91. 解码方法
# https://leetcode-cn.com/problems/decode-ways/
################################################################################
class Solution:
def numDecodings(self, s: str) -> int:
dp = [0] * (len(s) + 1)
dp[0] = 1
for i in range(len(s)):
if s[i] != "0":
dp[i + 1] += dp[i]
if i >= 1 and s[i - 1] != "0" and int(s[i - 1 : i + 1]) <= 26:
dp[i + 1] += dp[i - 1]
return dp[len(dp) - 1]
################################################################################
if __name__ == "__main__":
solution = Solution()
print(solution.numDecodings("06"))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25